Advanced Usage
進階用法
- 當table id是自動增加的,如何獲取id的值?
- 使用keyHolder
@PostMapping("/students")
public String create(@RequestBody Student student){
HashMap<String, Object> map = new HashMap<>();
//這邊value內冒號的寫法 jdbctemplate會把他當作key到map中取值後來當作sql參數
String sql = "Insert into student(name) VALUE (:studentName)";
//我們要根據key來建立我們希望sql放入的值 key-value = 上面的key名稱-我們希望的值(前端送入的值)
map.put("studentName", student.getName());
//建立一個keyholder來接自增主鑰
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
//map要改用MapSqlParameterSource並傳入map
namedParameterJdbcTemplate.update(sql, new MapSqlParameterSource(map), keyHolder);
return "create..."+"generated id:"+keyHolder.getKey().intValue();
}
- 如何大量執行一批 insert/update/delete ?
- 使用batchUpdate方法
@PostMapping("/students/batch")
public String insertList(@RequestBody List<Student> studentList) {
String sql = "INSERT INTO student(name) VALUE (:studentName)";
//建立MapSqlParameterSource List來存儲 studentList中的資訊
MapSqlParameterSource[] parameterSource = new MapSqlParameterSource[studentList.size()];
for (int i = 0; i < studentList.size(); i++) {
//針對每個元素放入parameterSource
Student student = studentList.get(i);
//key要與sql裡面的佔位符相等
parameterSource[i] = new MapSqlParameterSource().addValue("studentName", student.getName());
} namedParameterJdbcTemplate.batchUpdate(sql, parameterSource);
return "batch sql insert";
}